package com.fairytask.ui.pack
{
	import com.fairytask.data.ViewObject;
	import com.fairytask.engine.GameStage;
	import com.fairytask.engine.components.BaseItem;
	import com.fairytask.engine.components.ToolTips;
	import com.fairytask.engine.components.button.Button;
	import com.fairytask.engine.components.clip.Clip;
	import com.fairytask.engine.components.group.ViewGroup;
	import com.fairytask.engine.components.tab.TabBar;
	import com.fairytask.engine.components.tab.TabEvent;
	import com.fairytask.managers.ResManager;
	import com.fairytask.managers.TipsManage;
	import com.fairytask.resource.StaticIni;
	import com.fairytask.ui.InfoUI;
	import com.fairytask.ui.base.UnitUI;
	import com.fairytask.ui.item.BagItem;
	import com.fairytask.ui.item.InfoItem;
	import com.fairytask.ui.main.ChatUI;
	
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class PackageUI extends UnitUI
	{
		private static var _self:PackageUI;
		
		public var packGride	:ViewGroup;
		public var arrangeBtn	:Button;
		public var pageTab		:TabBar;

//		public var VIPBtn		:Button;
		
		public var showBtn		:Button;
		public var sellBtn		:Button;
		public var useBtn		:Button;
		public var btns		:Clip;
		
		private var _unbindArray	:Array=[];
		
		private var _bindObjs		:Array=[];
		private var _pageArr		:Array=[];
		private var _currPage		:int=1;
		private var _allPosNum		:int=35;
		private var _lockOffNum	:int=0;
		private var currIndex		:int;
		
		private var _vip:int;
		
		private var _curObj	:String;
		//双击标志
		private var _doubleClick	:Boolean = false;
		//消息框
		private var _infoUI		:InfoUI	=	InfoUI.getInstance();
		private var _infoItem	    :InfoItem;
		private var _maxAmount		:int;
		private var _nowDelect		:int=0;
		//记录鼠标经过的pos
		private var _VGOverPos	:int = -1;
		
		public function PackageUI()
		{			
			super();	
			init();
		}
		
		public static function getInstance():PackageUI
		{
			if(_self==null)
			{
				_self=new PackageUI();		
			} 
			return _self;
		}
		
		private function init():void
		{
			_infoItem	=	new InfoItem(checkInput);
			_infoItem.maxCharNum = 2;//物品删除个数最大位数为2位
			_infoItem.restrict = "0-9";
			
			lockListInit();
			initpack();
			initEvent();
			
			btns.visible=false;
		}
		
		private function initEvent():void
		{
			pageTab.addEventListener(TabEvent.TAB_CLICK,onPageChange);
			//整理
			arrangeBtn.addEventListener(MouseEvent.CLICK,onArrange);
			packGride.addItemsEvent(MouseEvent.CLICK,onShowBtnsOrExpandPack);
			packGride.addItemsEvent(MouseEvent.DOUBLE_CLICK,onUseObj);
			packGride.addItemsEvent(MouseEvent.ROLL_OVER,onItemOver);
			packGride.addItemsEvent(MouseEvent.ROLL_OUT,onItemOut);
			//点击其他地方隐藏按钮
			GameStage.stage.addEventListener(MouseEvent.MOUSE_UP,hideBtn);
			//展示
			showBtn.addEventListener(MouseEvent.CLICK,onShowObj);
			//出售
			sellBtn.addEventListener(MouseEvent.CLICK,onSellObj);
			//使用
			useBtn.addEventListener(MouseEvent.CLICK,onUseObject);
		}
		
		
		//初始化背包
		private function initpack():void
		{
//			bindManager.BindViewProp(model.scene.GetView(ViewDefine.VIEWPORT_PACKAGE),"Capacity",addCapacity);
//			bindManager.BindView(model.scene,ViewDefine.VIEWPORT_PACKAGE,addPackage,removePackage);
		}
		
		/**
		 * 点击背包格 
		 * @param e
		 * @param index
		 * 
		 */
		private function onShowBtnsOrExpandPack(e:MouseEvent,index:int):void	
		{
			currIndex=index;
			if(e.currentTarget.getItem()==null)
			{
				return;
			}
			//点击物品
			if(e.currentTarget.getItem() is BagItem)
			{
				_doubleClick = false;
				var curr:BagItem =(e.currentTarget as BaseItem).getItem() as BagItem;//物品这个对象
				btns.x=e.currentTarget.x+curr.width/2;
				btns.y=e.currentTarget.y+curr.height/2;
				var timer:Timer = new Timer(260,1);
				timer.addEventListener(TimerEvent.TIMER, checkClick);
				timer.start();
			}
			//扩展背包
			else
			{
				var currCol:int;
				var currStat:int=int(_lockOffNum/5);
				if((index+1)%5==0)
				{
					currCol=int((index+1)/5)+(_currPage-1)*7-currStat;
				}
				else
				{
					currCol=int((index+1)/5)+1+(_currPage-1)*7-currStat;	
				}
				//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_EXPAND_TOOL_BOX,currCol);				
			}
		}
		
		/**
		 * 双击物品 
		 * @param e
		 * @param index
		 * 
		 */
		private function onUseObj(e:MouseEvent,index:int):void
		{
			_doubleClick = true;
		}
		
		/**
		 * 单击双击判断
		 * @param evt
		 * 
		 */
		private function checkClick(evt:TimerEvent):void 
		{
			if(_doubleClick)
			{
				sendMessage();
				//隐藏tips
				ToolTips.hide();
			}
			else
			{
				if(!btns.visible)
				{
					btns.visible = true;
				}
				else
				{
					btns.visible = false;
				}
			}
		}
		
		/**
		 * 发送使用物品消息 
		 * 
		 */
		private function sendMessage():void
		{
			var	pos:int= currIndex+(_currPage-1)*_allPosNum;
			var amount:int=(packGride.getItemByIndex(currIndex).getItem() as BagItem).amount;
			//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_USEITEM,0,ViewDefine.VIEWPORT_PACKAGE,pos+1,amount,RoleListUI.getInstance().curObj);
		}
		
		/**
		 * viptips 
		 * @param evt
		 * @param idx
		 * 
		 */
		private function onVipOver(evt:MouseEvent):void
		{
			TipsManage.showTips(StaticIni.getSwfLangStr("1000000431"));
		}
		
		private function onVipOut(evt:MouseEvent):void
		{
			ToolTips.hide();
		}
		/**
		 * 鼠标移过 
		 * @param evt
		 * @param idx
		 * 
		 */
		private function onItemOver(evt:MouseEvent,idx:int):void
		{
			_VGOverPos = idx;
			var tmpItem :*	=	evt.currentTarget.getItem();
			if(null!=tmpItem)
			{
				if(tmpItem is BagItem)
				{
					//物品tips
					TipsManage.ShowAllItemsTips(int(StaticIni.getIniVar(tmpItem.configID,"ItemType")),tmpItem.configID,(tmpItem.data as ViewObject),true);
				}
				else
				{
					//锁，购买道具tips
					TipsManage.showTips(StaticIni.getSwfLangStr("1000000418"));
				}
			}
		}
		
		private function onItemOut(evt:MouseEvent,idx:int):void
		{
			_VGOverPos = -1;
			ToolTips.hide();
		}
		
		/**
		 * 点击其他地方隐藏菜单
		 * @param evt
		 * 
		 */		
		private function hideBtn(evt:MouseEvent):void
		{
			btns.visible=false;
		}
		
		/**
		 * 展示 
		 * @param e
		 * 
		 */
		private function onShowObj(e:MouseEvent):void
		{
			var	pos:int= currIndex+(_currPage-1)*_allPosNum;
			
			var viewObject		:ViewObject	=	(packGride.getItemByIndex(currIndex).getItem() as BagItem).data as ViewObject;
			var configId		:String		= viewObject.GetProperties("ConfigID");	//equip ID
			
			var color			:int;
			if(viewObject.CheckProperties("Color"))
			{
				color	=	viewObject.GetProperties("Color");
			}
			var equipName:String	=	StaticIni.getSwfLangStr(StaticIni.getIniVar(configId,"NameID"));
			equipName	=	"["+equipName+"]";
			ChatUI.getInstance().setEquipShow(equipName,int(configId),viewObject.objId,color);
			//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTMMSG_SHOW_EQUIP,viewObject.objId);
		}
		
		/**
		 * 使用物品
		 * @param e
		 * 
		 */
		private function onUseObject(e:MouseEvent):void
		{
			var	pos:int= currIndex+(_currPage-1)*_allPosNum;
			var amount:int=(packGride.getItemByIndex(currIndex).getItem() as BagItem).amount;
			//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_USEITEM,0,ViewDefine.VIEWPORT_PACKAGE,pos+1,amount,RoleListUI.getInstance().curObj);
		}
		
		/**
		 * 出售 
		 * @param e
		 * 
		 */
		private function onSellObj(e:MouseEvent):void
		{	
			var	pos:int= currIndex+(_currPage-1)*_allPosNum;
			var amount:int=(packGride.getItemByIndex(currIndex).getItem() as BagItem).amount;
			if(amount==0)
			{
				//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_USEITEM,2,ViewDefine.VIEWPORT_PACKAGE,pos+1);
			}
			else
			{
				_maxAmount = amount;
				_infoItem.text = String(_maxAmount);
				_infoUI.inputWithDesc(StaticIni.getSwfLangStr("1000000547"),_infoItem,InfoUI.CHOICEBTN,[onConfirm],InfoUI.INFOTXT);
			}
		}
		
		/**
		 * 检查输入框内容 
		 * @param str
		 * 
		 */
		private function checkInput(str:String):void
		{
			if(str.length==1)
			{
				if(int(str)==0)
				{
					_infoItem.text = "";
				}
			}
			//有最大个数限制
			if(int(str)>_maxAmount)
			{
				_infoItem.text = String(_maxAmount);
			}
			_nowDelect	=	int(_infoItem.text);
		}
		
		/**
		 * 确认出售 
		 * @param _data
		 * 
		 */
		private function onConfirm(_data:Array=null):void
		{
			if(_nowDelect!=0)
			{
				//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_USEITEM,2,ViewDefine.VIEWPORT_PACKAGE,currIndex+(_currPage-1)*_allPosNum+1,_nowDelect);
				_nowDelect = 0;
			}
		}
		
		//改变页数
		private function onPageChange(e:TabEvent):void
		{
			onPage(e.item.id+1);
		}
		
		/**
		 * 切换页面内容 
		 * @param num
		 * 
		 */
		private function onPage(num:int):void
		{
			_currPage=num;
			//删除所有的数据
			removeAll();	
			//当前位置
			var posNow:int = (_currPage-1)*_allPosNum+1;
			//第2-4栏加锁显示
			if(_currPage<=4)
			{
				lockListInit();//先全部加锁
			}
			lockListFilter();//然后解锁已经开锁的
			//填写当前页面的数据
			for (var i:int=(_currPage-1)*_allPosNum+1;i <=_currPage*_allPosNum;i++)
			{
				if(_bindObjs[i]!=null)
				{
					addObj(_bindObjs[i],i);
				}
			}
		}
		
		/**
		 * 解锁 
		 * 
		 */
		private function lockListFilter():void
		{
			var i:int;
			var baseItem:BaseItem;
			/*if(_currPage*_allPosNum>=_lockOffNum)
			{
				for (i=0;i<_lockOffNum-(_currPage-1)*_allPosNum;i++)
				{
					baseItem		=	packGride.getItemByIndex(i);
					baseItem.clear();
				}
			}
			else
			{
				for (i=0;i<_allPosNum;i++)
				{
					baseItem		=	packGride.getItemByIndex(i);
					baseItem.clear();
				}
			}*/
			for (i=0;i<_lockOffNum-(_currPage-1)*_allPosNum;i++)
			{
				baseItem		=	packGride.getItemByIndex(i);
				if(null != baseItem.getItem())
				{
					if(baseItem.getItem() is BagItem)
					{
						
					}
					else if(baseItem.getItem() is MovieClip)
					{
						baseItem.clear();
					}
				}
			}
		}
		
		/**
		 * 加锁
		 * 
		 */
		private function lockListInit():void
		{
			packGride.getItemForEach(function (item:BaseItem):void
			{
				item.clear();
				var lock : MovieClip=	ResManager.newResClass("Lock_001") as MovieClip;
				lock.x	=	6;
				lock.y	=	5;
				item.addItem(lock);
			});
		}
		private function removeAll():void
		{
			for(var i:int=0;i<_allPosNum;i++)
			{
				packGride.getItemByIndex(i).clear();
			}
		}
		
		//整理背包
		private function onArrange(e:MouseEvent):void
		{
			arrangeBtn.enabled	=	false;
			//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_ARANGEITEM,ViewDefine.VIEWPORT_PACKAGE);
		}
		//初始化
		
		//初始化角色属性
		
		private function addCapacity(key:String,val:int):void
		{
			if(_lockOffNum == val)
			{
				return;
			}
			_lockOffNum=val;
			lockListFilter();
		}
		
		//添加物品
		private function addPackage(key:String, val:*, data:Object):void
		{
			if(val.GetPropertiesEx("ConfigID")=="")
			{
				return;
			}
			var pos:int=val.GetProperties("Pos");
			
			if(propsPage(pos)==_currPage)
			{
				addObj(val);
			}
			_bindObjs[pos]=val;
		}
		
		/**
		 *	获取物品的当前的页数 
		 * @param pos		服务器发过来的位置从1开始
		 * @return 
		 * 
		 */		
		private function propsPage(pos:int):int
		{
			var page	:int;
			if(pos%_allPosNum==0)
			{
				page=pos/_allPosNum;
			}
			else
			{
				page=pos/_allPosNum+1;
			}
			return page;
		}
		
		/**
		 * 获取物品当前页位置 
		 * @param _pos
		 * @return 
		 * 
		 */
		private function propsPos(_pos:int):int
		{
			if(_pos%_allPosNum==0)
			{
				_pos=_allPosNum-1;
			}
			else
			{
				_pos=_pos%_allPosNum-1;
			}
			return _pos;
		}
		
		/**
		 * 添加物品到物品栏
		 * @param val
		 * @param pos
		 * 
		 */
		private function addObj(val:ViewObject,pos:int=0):void
		{
			var obj:BagItem=new BagItem(val);
			var posIndex:int = val.GetProperties("Pos");
			if(pos!=0)
			{
				posIndex = pos;
			}
			var index:int = propsPos(posIndex);
			if(val.CheckProperties("Amount"))
			{
				_unbindArray[posIndex] = [val,"Amount",bindManager.BindObjProp(val,"Amount",setGoodNum,[obj])];
			}
			packGride.getItemByIndex(index).clear();
			packGride.getItemByIndex(index).addItem(obj);
			//鼠标位置和当前相同时，刷新tips
			/*if(_VGOverPos == index)
			{
				packGride.getItemByIndex(index).dispatchEvent(new MouseEvent(MouseEvent.ROLL_OVER));
			}*/
		}
		
		/**
		 * 绑定物品数量，按格式要求显示:如 _1、11
		 * @param PropertiesName
		 * @param PropertiesValue
		 * @param pList
		 * 
		 */		
		private function setGoodNum(key:String,val:int,pList:Array):void
		{
			var obj:BagItem = pList[0] as BagItem;
			obj.amount = val;
		}
		
		/**
		 * 移除物品
		 * @param key
		 * @param val
		 * @param data
		 * 
		 */
		private function removePackage(key:String, val:*, data:Object):void
		{
			var pos:int=val.GetProperties("Pos");
		
			if(_bindObjs[pos]!=null&&(_bindObjs[pos] as ViewObject).ObjKey==key)
			{
				_bindObjs[pos]=null;
			}
			//解绑数量
			if(_unbindArray[pos])
			{
				if(_unbindArray[pos].length > 0)
				{
					bindManager.UnbindProp(_unbindArray[pos].shift(),_unbindArray[pos].shift(),_unbindArray[pos].shift());
				}
				_unbindArray[pos] = [];
			}
			if(propsPage(pos)==_currPage)
			{
				packGride.getItemByIndex(propsPos(pos)).clear();
			}
		}
		
		/**
		 * 重置 
		 * 
		 */
		override public function reset():void
		{
			arrangeBtn.enabled	=	true;
		}
		
		public function set curObj(val:String):void
		{
			_curObj = val;
		}
	}
}